#!/usr/bin/env python
import os, sys, shutil, fileinput
import random, readline, rlcompleter
import string as pystring
from subprocess import call
import psycopg2

# Default configuration
PROJECT_DIR = "/usr/share/projects/"
DB_USER = 'nobody'
DB_PASSWD = ''
DB_HOST = '192.168.2.4'

MY_DIR = os.path.abspath(os.path.dirname(__file__))
SKEL_DIR = os.path.join(MY_DIR, "skel")
PROJECT_NAME = '' # Get from command-line options maybe?
PROJECT_DOMAIN = ''
SECRET_KEY = "".join([random.choice("abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)") for i in range(50)])

def personalizeFile(fn):
	for line in fileinput.input(fn, inplace=1):
		line = line.replace("TEMPROJECT", PROJECT_NAME)
		if fn.endswith("settings.py"):
			line = line.replace("DBUSER", DB_USER)
			line = line.replace("DBPASSWD", DB_PASSWD)
			line = line.replace("SECRETKEY", SECRET_KEY)
		if fn.endswith(".conf"):
			line = line.replace("PROJECTPATH", PROJECT_PATH)
			line = line.replace("PRDOMAIN", PROJECT_DOMAIN)
		print line.rstrip()

def personalizeDir(dir):
	for fn in os.listdir(dir):
		if fn.endswith(".py"):
			fp = os.path.join(dir, fn)
			personalizeFile(fp)

class FileNameCompleter(rlcompleter.Completer):
	def file_matches(self, text):
		matches = []
		path, name = os.path.split(text)
		try:
			for fn in os.listdir(path or os.curdir):
				if fn[:len(name)] == name:
					full = os.path.join(path, fn)
					matches.append(full)
					if os.path.isdir(full):
						matches += map(lambda x: os.path.join(full, x), os.listdir(full))
		except OSError:
			pass
		return matches
	def global_matches(self, text):
		return self.file_matches(text)

readline.set_completer(FileNameCompleter().complete)
readline.set_completer_delims(pystring.replace(readline.get_completer_delims(), os.sep, ''))
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')

while not os.path.exists(PROJECT_DIR):
	print "Project directory '%s' does not exist." % PROJECT_DIR
	PROJECT_DIR = raw_input('Where are your projects stored? ("QUIT" to exit): ')
	if PROJECT_DIR == 'QUIT':
		sys.exit()

print "Using project directory '%s'..." % PROJECT_DIR

while True:
	PROJECT_NAME = raw_input('What will the project be called? ("QUIT" to exit): ')
	if PROJECT_NAME == 'QUIT':
		sys.exit()
	PROJECT_NAME = PROJECT_NAME.replace(" ","")
	PROJECT_PATH = os.path.join(PROJECT_DIR, PROJECT_NAME)
	if os.path.exists(PROJECT_PATH):
		print "This project path alreday exists ('%s')." % PROJECT_PATH
	else:
		os.mkdir(PROJECT_PATH)
		print "Created directory '%s'." % PROJECT_PATH
		break

while not DB_PASSWD:
	DB_PASSWD = raw_input('What is the password for database user "%s"? ("QUIT" to exit"): ' % DB_USER)
	if DB_PASSWD == 'QUIT':
		sys.exit()

while not PROJECT_DOMAIN:
	PROJECT_DOMAIN = raw_input('What is the domain name for this project? (without "www"): ')
	if PROJECT_DOMAIN == 'QUIT':
		sys.exit()

print "Copying files..."
shutil.copytree(os.path.join(SKEL_DIR, "media"), os.path.join(PROJECT_PATH, "media"))
shutil.copytree(os.path.join(SKEL_DIR, "templates"), os.path.join(PROJECT_PATH, "templates"))
PROJECT_BASE = os.path.join(PROJECT_PATH, PROJECT_NAME)
shutil.copytree(os.path.join(SKEL_DIR, "TEMPROJECT"), PROJECT_BASE)

print "Personalizing..."
personalizeFile(PROJECT_BASE + "/settings.py")
personalizeDir(PROJECT_BASE)
personalizeDir(os.path.join(PROJECT_BASE, "frontend"))

print "Configuring apache virtual host..."
LOG_DIR = os.path.join("/var/log/apache2/", PROJECT_NAME)
os.mkdir(LOG_DIR)
A2_CONF = "/etc/apache2/sites-available/%s.conf" % PROJECT_NAME
shutil.copyfile(SKEL_DIR + "/vhost.conf", A2_CONF)
personalizeFile(A2_CONF)
call(["a2ensite", "%s.conf" % PROJECT_NAME])

print "Creating database '%s' on host '%s' ... " % (PROJECT_NAME, DB_HOST)
connection = psycopg2.connect("dbname=postgres user=%s password=%s host=%s" % (DB_USER, DB_PASSWD, DB_HOST))
cursor = connection.cursor() 
connection.set_isolation_level(0)
try: 
	cursor.execute("CREATE DATABASE %s" % PROJECT_NAME) 
except Exception, e: 
	sys.stderr.write("Got an error creating the test database: %s\n" % e)
	sys.exit()

print "[TODO] Please add a DNS record for '%s'!" % (PROJECT_DOMAIN)

os.chdir(PROJECT_BASE)
print "Restarting apache..."
call(["apache2ctl", "restart"])
print "We are done.  Visit your new project at: http://%s and have fun!" % PROJECT_DOMAIN
